import sqlite3
from flask import *
import os

app = Flask(__name__)


app.config['USERNAME']='finance'#账号密码
app.config['PASSWORD']='finance'

app.secret_key=os.urandom(24)

@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            flash('You were logged in')
            return redirect(url_for('index'))
    return render_template('login.html', error=error)

@app.route('/logout')
def logout():
    session.pop('logged_in', None)
    flash('You were logged out')
    return redirect(url_for('login'))


def get_db():
    db = sqlite3.connect('test.db')
    db.row_factory = sqlite3.Row
    return db


def query_db(query, one=False):#, args=()
    db = get_db()
    cur = db.execute(query)#, args
    db.commit()
    rv = cur.fetchall()
    db.close()
    return (rv[0] if rv else None) if one else rv


@app.route("/", methods=["GET"])
def index():
    if session.get('logged_in'):
        return render_template("index.html")
    else:
        return redirect(url_for('login'))
    

@app.route("/finance", methods=["POST"])
def finance():
    if request.method == "POST":
        res = query_db("SELECT * FROM tick_data ") 
        print(int(request.form['id']))
    return jsonify(time = [x[32] for x in res],
                   price = [x[4] for x in res]) # 返回json格式



if __name__ == "__main__":
    app.run()#debug=True
